package com.jy.project.service.imp;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.jy.project.controller.ApplyController;
import com.jy.project.controller.MatericalController;
import com.jy.project.domain.*;
import com.jy.project.dto.*;
import com.jy.project.enums.ApplyTypeEnum;
import com.jy.project.enums.ApplyTypeMatericalEnum;
import com.jy.project.enums.QualityStatusEnum;
import com.jy.project.ex.BizException;
import com.jy.project.mapper.*;
import com.jy.project.service.ApplyService;
import com.jy.project.service.imp.defult.DefaultApplyBusinessImp;
import com.jy.project.util.*;
import com.jy.project.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service("applyReturnServiceImpl")
@Slf4j
public class ApplyReturnServiceImpl extends DefaultApplyBusinessImp implements ApplyService {

    @Autowired
    private ApplyMapper applyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private ApplyBorrowMapper applyBorrowMapper;


    @Autowired
    private ApplyReturnMapper applyReturnMapper;

    @Autowired
    DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    TransactionDefinition transactionDefinition;


    @Override
    public boolean insertApply(ApplyDTO dto) {
        dto.setApplyType(ApplyTypeEnum.RETURN.getCode());
        Set<Integer> set = new HashSet<>();
        set.add(dto.getApplyType());
        dto.setExt(JSONObject.toJSONString(set));
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            boolean bl = this.insertApplyBusiness(dto);
            if (bl == false) {
                throw new BizException("申请借用失败");
            }
        } catch (Exception e) {
            dataSourceTransactionManager.rollback(transactionStatus);
            throw e;
        }
        dataSourceTransactionManager.commit(transactionStatus);
        return true;
    }

    @Override
    public List<ApplyQualitVO> listApplyQualityVO(ApplyQueryDTO dto) {

        return applyMapper.listApplyyQualityVO(dto);
    }

    @Override
    public List<ApplyDeptAdminVO> listDeptAdminApplyVO(ApplyDeptAdminQueryDTO dto) {
        return null;
    }

    @Override
    public boolean applyAdopt(ApplyAdoptDTO dto) {
        log.info("审批通过归还单");
        String applyNo = dto.getApplyNo();
        Apply apply = applyMapper.getApplyByApplyNo(applyNo);
        if (apply==null){
            throw  new BizException("申请单不存在");
        }
        Example example =new Example(ApplyRenew.class);
        example.createCriteria().andEqualTo("applyNo",dto.getApplyNo());
        List<ApplyReturn> list = applyReturnMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)){
            throw  new BizException("数据不存在");
        }
        List<String> materialNos=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            materialNos.add(list.get(i).getMaterialNo());
        }
        ApplyUpdateDTO applyUpdateCollectDTO=new ApplyUpdateDTO();
        String s = CommonStringUtils.toStr(materialNos);
        applyUpdateCollectDTO.setMaterialNos(s);
        applyUpdateCollectDTO.setUseStatus(0);
        applyUpdateCollectDTO.setUseCompanyNo("");
        applyUpdateCollectDTO.setUseCompanyName("");
        applyUpdateCollectDTO.setUseDeptNo("");
        applyUpdateCollectDTO.setUseDeptName("");
        applyUpdateCollectDTO.setUseUserId(0L);
        applyUpdateCollectDTO.setUseNickName("");
        return materialMapper.updateStatusMaterialNos(s,0)>0;
    }

    @Override
    public boolean applyReject(ApplyAdoptDTO dto) {
        log.info("驳回通过归还单");
        return true;
    }

    @Override
    public ServiceResultUtils listMaterialDetailsVO(MaterialDetailsDTO dto) {
        return null;
    }

    @Override
    public List<ApplyUserVO> listUserApplyVO(ApplyUserQueryDTO dto) {
        return null;
    }


    @Override
    public void checkApplyNo(String applyNo) {


    }

    protected Apply getApply(String applyNo) {
        if (StringUtils.isEmpty(applyNo)) {
            throw new BizException("借用单号不能为空");
        }
        Example example = new Example(Apply.class);
        example.createCriteria().andEqualTo("isDelete", 0)
                .andEqualTo("applyNo", applyNo);
        Apply apply = applyMapper.selectOneByExample(example);
        if (apply == null) {
            throw new BizException("该借用单申请信息不存在");
        }
        return apply;
    }

    @Override
    public MaterialVO checkMaterialNo(String materialNo) {
        return super.checkMaterialNo(materialNo);
    }

    @Override
    public boolean insertApplyBusiness(ApplyDTO dto) {
        if (dto == null) {
            throw new BizException("Apply对象为空");
        }
        Apply apply = getApply(dto.getApplyNo());
        Apply ay = new Apply();
        ay.setApplyNo(CodeUtils.generateApplyNo(ApplyTypeMatericalEnum.RETURN.getValue()));
        BeanUtils.copyProperties(apply,ay);
        Date date = new Date();
        ay.setCreateAt(date);
        ay.setUpdateAt(date);
        ay.setUpdateDay(date);
        ay.setIsDelete(0);
        ay.setApplyType(ApplyTypeEnum.RETURN.getCode());
        ay.setName(ApplyTypeEnum.getValue(ay.getApplyType()));
        //制单人
        String token = dto.getToken();
        User u = JwtUtils.verifyToken(token);
        Long id = u.getId();
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            throw new BizException("用户信息可能找不到");
        }
        MaterialDetailsDTO materialDetailsDTO = new MaterialDetailsDTO();
        materialDetailsDTO.setApplyNo(dto.getApplyNo());
        List<MaterialDetailsVO> materialDetailsVOS = applyBorrowMapper.listMaterialDetailsVO(materialDetailsDTO);
        if (CollectionUtils.isEmpty(materialDetailsVOS)){
            throw new BizException("找不到退库数据");
        }
        String[] split=new String[materialDetailsVOS.size()];
        for (int i = 0; i < materialDetailsVOS.size(); i++) {
            split[i]=(materialDetailsVOS.get(i).getMaterialNo());
        }
        checkMaterialNos(split);
        ay.setId(null);
        ay.setApplicantCompanyNo(user.getCompanyNo());
        ay.setApplicantCompanyName(user.getCompanyName());
        ay.setApplicantDeptNo(user.getDeptNo());
        ay.setApplicantDeptName(user.getDeptName());
        ay.setApplicantUserId(user.getId());
        ay.setApplicantUserNickName(user.getNickName());
        ay.setExt(dto.getExt());
        ay.setStatus(0);
        ay.setRemarks(dto.getRemarks());
        ApplyReturnDTO applyRenewDTO = (ApplyReturnDTO) dto;
        List<String> list = Arrays.asList(split);
        Example example = new Example(ApplyBorrow.class);
        example.createCriteria()
                .andEqualTo("isDelete", 0)
                .andEqualTo("useUserId", dto.getUseUserId())
                .andEqualTo("applyType",ApplyTypeEnum.BORROW.getCode())
                .andIn("materialNo", list);
        List<ApplyBorrow> applyBorrows = applyBorrowMapper.selectByExample(example);
        if (applyBorrows == null) {
            throw new BizException("找不到当前使用者的借用单");
        }
        List<ApplyReturn> applyReturns = new ArrayList<>();
        for (int i = 0; i < applyBorrows.size(); i++) {
            ApplyBorrow applyBorrow = applyBorrows.get(i);
            ApplyReturn applyReturn =new ApplyReturn();
            BeanUtils.copyProperties(applyBorrow,applyReturn);
            applyReturn.setId(null);
            applyReturn.setStatus(0);
            applyReturn.setApplyNo(ay.getApplyNo());
            applyReturn.setApplyType(ay.getApplyType());
            applyReturn.setName(ay.getName());
            applyReturns.add(applyReturn);
        }
        applyReturnMapper.insertList(applyReturns);
        applyMapper.insertSelective(ay);
        return  true;
    }

    private List<MaterialVO> checkMaterialNos(String[] split) {
        String s = CommonStringUtils.toStr(split);
        List<MaterialVO> materialVOS = materialMapper.listMaterialVOByMaterialNos(s);

        for (int i = 0; i < materialVOS.size(); i++) {
            MaterialVO materialVO = materialVOS.get(i);
            String[] qualityStatus = materialVO.getQualityStatus();
            if (qualityStatus!=null ||qualityStatus.length>0) {
                boolean bl = false;
                for (int j = 0; j < qualityStatus.length; j++) {
                    String qStatus = qualityStatus[j];
                    if (qStatus.equals(QualityStatusEnum.REFUNDABLE.getCode())) {
                        bl = true;
                    }
                }
                if (bl == false) {
                    throw new BizException("编号[" + materialVO.getMaterialNo() + "]资产质量状态设置不可退库");

                }
            }

        }
        return materialVOS;
    }
}